<template>
  <div>
    <yt-crud
      v-bind="options"
      ref="crudRef"
      @onLoad="getData"
      :fun-props="{
        exportBtn: false,
        delBtn: false,
        addBtn: false,
      }"
      :table-props="{
        selection: false,
        delBtn: false,
        viewBtn: true,
        editBtn: false,
        menuSlot: true,
        menuWidth: 200,
        viewPermi: ['business:customer:query'],
      }"
      :loading="state.loading"
      :total="state.total"
      v-model:page="state.page"
      v-model:query="state.query"
      @delFun="handleDelete"
      @saveFun="onSave"
      @change="onChange"
      @openBeforeFun="openBeforeFun"
    >
      <template #leftToolbar></template>
      <template #rightToolbar></template>
      <template #menuSlot></template>
      <template #status="scope:any">
        <DictTag :options="EnableStatusEnum" :value="scope.row.status" />
      </template>
      <template #type="scope:any">
        <DictTag :options="CustomerTypeEnum" :value="scope.row.type" />
      </template>
      <template #quotaAmount="scope:any">
        <el-tooltip :content="t('business.customer.quotaAmount')" placement="top">
          <el-button link type="primary" @click="handleQuotaList(scope.row)" :style="{cursor: 'pointer'}">
            {{scope.row.quotaTotalAmount || '-'}}
          </el-button>
        </el-tooltip>
      </template>
    </yt-crud>
    <QuotaList ref="quotaRef" />
  </div>
</template>

<script lang="ts" setup>
import { IColumn } from '@/components/common/types/tableCommon'
import {getCustomerList, deleteCustomer, batchDeleteCustomer, saveCustomer, batchRestoreCustomer } from '@/api/business/customer'

import YtCrud from '@/components/common/yt-crud.vue'
import {ComponentInternalInstance} from 'vue'
import {useI18n} from 'vue-i18n'
import QuotaList from './modules/QuotaList.vue'
import constants from '@/constants'
import { ArrowDown } from '@element-plus/icons-vue'

const { t } = useI18n()

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { EnableStatusEnum, CustomerTypeEnum } = toRefs<any>(proxy?.useEnum('enable_status_enum', 'customer_type_enum'))

const quotaRef = ref()

const state = reactive({
  page: {
    pageNum: 1,
  },
  total: 0,
  loading: false,
  query: {},
})

const column = ref<IColumn[]>([
  {
    label: t('business.customer.userName'),
    key: 'userName',
    rules: [
      { required: true, message: t('business.customer.validator.userName') },
      { min: 11, max: 11, trigger: 'blur', message: t('business.customer.validator.userName') },
      { pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/, message: t('business.customer.validator.userName') }
    ],
    searchLabelWidth: 120,
    search: true,
    formHide: false,
    editDisabled: true,
    colSpan: 22,
    align: 'center',
  },
  {
    label: t('business.customer.nickName'),
    key: 'nickName',
    searchLabelWidth: 120,
    search: true,
    formHide: true,
    colSpan: 22,
    align: 'center',
  },
  {
    label: t('business.customer.type'),
    key: 'type',
    type: 'select',
    rules: [{ required: true, message: t('business.customer.validator.type') }],
    componentProps: {
      options: CustomerTypeEnum,
    },
    search: true,
    formHide: false,
    slot: true,
    align: 'center',
  },
  {
    label: t('business.customer.topupAmount'),
    key: 'topupAmount',
    type: 'number',
    search: false,
    formHide: true,
    editDisabled: true,
    slot: false,
    align: 'right',
  },
  {
    label: t('business.customer.settleAmount'),
    key: 'settleAmount',
    type: 'number',
    search: false,
    formHide: true,
    editDisabled: true,
    slot: false,
    align: 'right',
  },
  {
    label: t('business.customer.balanceAmount'),
    key: 'balanceAmount',
    type: 'number',
    search: false,
    formHide: true,
    editDisabled: true,
    slot: false,
    align: 'right',
  },
  {
    label: t('business.customer.giveAmount'),
    key: 'giveAmount',
    type: 'number',
    search: false,
    formHide: true,
    editDisabled: true,
    slot: false,
    align: 'right',
  },
  {
    label: t('business.customer.quotaAmount'),
    key: 'quotaAmount',
    type: 'number',
    hide: false,
    search: false,
    formHide: true,
    editDisabled: true,
    slot: true,
    align: 'right',
  },
  {
    label: t('business.customer.refundedAmount'),
    key: 'refundedAmount',
    type: 'number',
    hide: false,
    search: false,
    formHide: true,
    editDisabled: true,
    slot: false,
    align: 'right',
  },
  {
    label: t('business.customer.status'),
    key: 'status',
    type: 'select',
    rules: [{ required: true, message: t('business.customer.validator.status') }],
    componentProps: {
      options: EnableStatusEnum,
    },
    search: true,
    formHide: false,
    slot: true,
    align: 'center',
  },
  {
    label: t('business.customer.loginDate'),
    key: 'loginDate',
    tableWidth: 180,
    sortable: true,
    type: 'date',
    formHide: true,
    align: 'center',
  },
  {
    label: t('crud.table.column.createTime'),
    key: 'createTime',
    tableWidth: 180,
    sortable: true,
    type: 'date',
    formHide: true,
    align: 'center',
  },
  {
    label: t('crud.table.column.note'),
    key: 'note',
    hide: true,
    formHide: false,
    colSpan: 22,
    componentProps: {
      type: 'textarea',
      rows: 2,
    }
  },
])
const crudRef = ref()
const data = ref<any[]>([])
const getData = () => {
  state.loading = true
  getCustomerList({
    ...state.page,
    ...state.query,
  })
    .then((res) => {
      data.value = res.data.rows
      state.total = res.data.total
    })
    .finally(() => {
      state.loading = false
    })
}


const getDict = () => {
}
getDict()


// 弹窗前置操作
const openBeforeFun = ({ type, data }) => {
  if (type === 'add') {
    data.status = 'Enabled'
    data.type = 'Wechat'
  } else if (type === 'update') { /* empty */ }
}

// 保存数据
const onSave = async ({ data, cancel }: any) => {
  state.loading = true
  data.mobile = data.userName
  data.nickName = data.userName
  saveCustomer(toRaw(data)).then(()=>{
    cancel()
    getData()
  }).finally(()=>{
    state.loading = false
  })
}

// 删除
const handleDelete = async (row: any) => {
  state.loading = true
  if (row instanceof Array) {
    batchDeleteCustomer(row.map((m) => m.id)).then(()=>{
      ElMessage.success(t('operate.tooltip.success'))
      getData()
    }).finally(()=>{
      state.loading = false
    })
  } else {
    await deleteCustomer(row.id).then(()=>{
      ElMessage.success(t('operate.tooltip.success'))
      getData()
    }).finally(()=>{
      state.loading = false
    })
  }
}

const handleQuotaList = (row: any) => {
  quotaRef.value.openDialog(row)
}

const handleBatchOperate = (command: string ) => {
  switch (command) {
    case 'batchRestore':
      handleBatchRestore()
      break
  }
}

const handleBatchRestore = async () => {
  await proxy?.$modal.confirm(t('business.customer.tooltip.batchRestore'))
  state.loading = true
  batchRestoreCustomer(multipleSelection.value.map(element => element.id)).then(() => {
    ElMessage.success(t('operate.tooltip.success'))
    getData()
  }).finally(() => {
    state.loading = false
  })
}


const multipleSelection = ref<any[]>([])

const onChange = (data: any) => {
  multipleSelection.value = data
}

const options = reactive({
  ref: 'crudRef',
  data,
  column,
})
</script>

<style lang="scss" scoped></style>
